package model;

import databaseHandling.BrugerHandler;
import interfaces.BrugerInterface;
import interfaces.ConnectionInterface;
import interfaces.GourmetGrossistInterface;
import interfaces.RemoteActionInterface;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Maja
 */
public class GourmetGrossist extends UnicastRemoteObject implements GourmetGrossistInterface {

    private static GourmetGrossist instance;
    private ArrayList<ConnectionInterface> connections;

    private GourmetGrossist() throws RemoteException {
        connections = new ArrayList<>();
    }

    public static GourmetGrossist getInstance() throws RemoteException {
        if (instance == null) {
            instance = new GourmetGrossist();
        }
        return instance;
    }

    @Override
    public ConnectionInterface getConnection(String username, String password) throws RemoteException, SQLException {

        ConnectionInterface connectionInterface = null;
        BrugerInterface brugerInterface = BrugerHandler.getBruger(username);
        if (password.equals(brugerInterface.getPassword())) {
            connectionInterface = new Connection(brugerInterface);
            addConnection(connectionInterface);
        }
        return connectionInterface;

    }

    @Override
    public void addConnection(ConnectionInterface c) throws RemoteException {
        connections.add(c);
    }

    @Override
    public void removeActionListener(ConnectionInterface c) throws RemoteException {
        connections.remove(c);
    }

    @Override
    public void notifyListeners(RemoteActionInterface rai) throws RemoteException {
        System.out.println("Antal conns:" + connections.size());
        for (ConnectionInterface connectionInterface : connections) {
            connectionInterface.getObserverListener().notifyClient(rai);
            System.out.println("Vi notifyer connection: " + connectionInterface.getBruger().getBrugernavn());
        }
    }

}
